import { createSlice, createAsyncThunk,createEntityAdapter,createSelector } from '@reduxjs/toolkit'
import axios from 'axios'

const todoAdapter = createEntityAdapter({
  selectId: todo=> todo.cid
})
console.log(todoAdapter.getInitialState())

export const TODOS_FEATURE_KEY = 'todos'

export const loadTodos = createAsyncThunk('todos/loadTodos',payload =>{
  return axios.get(payload).then(response=> response.data)
})

const { reducer: TodosReducer, actions } = createSlice({
  name: TODOS_FEATURE_KEY,
  initialState: todoAdapter.getInitialState(),
  extraReducers: {
    [loadTodos.pending]: (state,action) => {
      console.log('pending')
      return state
    },
    [loadTodos.fulfilled]: todoAdapter.addMany
  },
  reducers: {
    addTodo: {
      reducer: todoAdapter.addOne,
      // 预处理
      prepare: todo => {
        return {
          payload:{
            cid: Math.random(),
            ...todo
          }
        }
      }
    },
    setTodos: todoAdapter.addMany
  }
})

const { selectAll } = todoAdapter.getSelectors()

export const selectTodos = createSelector(state=> state[TODOS_FEATURE_KEY],selectAll)

export const { addTodo, setTodos } = actions 
export default TodosReducer